<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="800px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="loading"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="检查编号" prop="inspectionCode">
            <el-input v-model="formData.inspectionCode" placeholder="请输入检查编号" :disabled="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="水库名称" prop="reservoirName">
            <el-select v-model="formData.reservoirName" placeholder="请选择水库" :disabled="isView" style="width: 100%">
              <el-option label="东圳水库" value="东圳水库" />
              <el-option label="金钟水库" value="金钟水库" />
              <el-option label="西音水库" value="西音水库" />
              <el-option label="太平水库" value="太平水库" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="检查类型" prop="inspectionType">
            <el-select v-model="formData.inspectionType" placeholder="请选择检查类型" :disabled="isView" style="width: 100%">
              <el-option label="日常检查" value="daily" />
              <el-option label="定期检查" value="regular" />
              <el-option label="专项检查" value="special" />
              <el-option label="应急检查" value="emergency" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="检查时间" prop="inspectionDate">
            <el-date-picker
              v-model="formData.inspectionDate"
              type="date"
              placeholder="请选择检查时间"
              :disabled="isView"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="检查人员" prop="inspector">
            <el-input v-model="formData.inspector" placeholder="请输入检查人员" :disabled="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="检查状态" prop="status">
            <el-select v-model="formData.status" placeholder="请选择状态" :disabled="isView" style="width: 100%">
              <el-option label="待检查" value="pending" />
              <el-option label="检查中" value="checking" />
              <el-option label="已完成" value="completed" />
              <el-option label="异常" value="abnormal" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="发现问题数" prop="issueCount">
            <el-input-number v-model="formData.issueCount" :min="0" :disabled="isView" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="检查等级" prop="level">
            <el-select v-model="formData.level" placeholder="请选择检查等级" :disabled="isView" style="width: 100%">
              <el-option label="一级" value="1" />
              <el-option label="二级" value="2" />
              <el-option label="三级" value="3" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="检查结果" prop="result">
        <el-input
          v-model="formData.result"
          type="textarea"
          :rows="4"
          placeholder="请输入检查结果"
          :disabled="isView"
        />
      </el-form-item>
      
      <el-form-item label="问题描述" prop="issueDescription">
        <el-input
          v-model="formData.issueDescription"
          type="textarea"
          :rows="3"
          placeholder="请输入发现的问题描述"
          :disabled="isView"
        />
      </el-form-item>
      
      <el-form-item label="处理建议" prop="suggestion">
        <el-input
          v-model="formData.suggestion"
          type="textarea"
          :rows="3"
          placeholder="请输入处理建议"
          :disabled="isView"
        />
      </el-form-item>
      
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入备注信息"
          :disabled="isView"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button v-if="!isView" type="primary" @click="handleSubmit" :loading="loading">
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'

// Props
interface Props {
  modelValue: boolean
  title: string
  inspectionData?: any
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  title: '新增检查',
  inspectionData: null
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  success: []
}>()

// 模拟API接口
const saveInspection = async (data: any) => {
  // 模拟保存
  return { code: 200, msg: '保存成功' }
}

const updateInspection = async (data: any) => {
  // 模拟更新
  return { code: 200, msg: '更新成功' }
}

// 响应式数据
const loading = ref(false)
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive({
  id: null,
  inspectionCode: '',
  reservoirName: '',
  inspectionType: '',
  inspectionDate: '',
  inspector: '',
  status: 'pending',
  issueCount: 0,
  level: '',
  result: '',
  issueDescription: '',
  suggestion: '',
  remark: ''
})

// 表单验证规则
const formRules: FormRules = {
  inspectionCode: [
    { required: true, message: '请输入检查编号', trigger: 'blur' }
  ],
  reservoirName: [
    { required: true, message: '请选择水库名称', trigger: 'change' }
  ],
  inspectionType: [
    { required: true, message: '请选择检查类型', trigger: 'change' }
  ],
  inspectionDate: [
    { required: true, message: '请选择检查时间', trigger: 'change' }
  ],
  inspector: [
    { required: true, message: '请输入检查人员', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择检查状态', trigger: 'change' }
  ],
  result: [
    { required: true, message: '请输入检查结果', trigger: 'blur' }
  ]
}

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const isEdit = computed(() => props.inspectionData && props.inspectionData.id)
const isView = computed(() => props.title.includes('查看'))

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    inspectionCode: '',
    reservoirName: '',
    inspectionType: '',
    inspectionDate: '',
    inspector: '',
    status: 'pending',
    issueCount: 0,
    level: '',
    result: '',
    issueDescription: '',
    suggestion: '',
    remark: ''
  })
  
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 填充表单数据
const fillFormData = (data: any) => {
  Object.assign(formData, {
    id: data.id,
    inspectionCode: data.inspectionCode || '',
    reservoirName: data.reservoirName || '',
    inspectionType: data.inspectionType || '',
    inspectionDate: data.inspectionDate || '',
    inspector: data.inspector || '',
    status: data.status || 'pending',
    issueCount: data.issueCount || 0,
    level: data.level || '',
    result: data.result || '',
    issueDescription: data.issueDescription || '',
    suggestion: data.suggestion || '',
    remark: data.remark || ''
  })
}

// 监听弹窗显示状态
watch(visible, (newVal) => {
  if (newVal) {
    if (props.inspectionData) {
      fillFormData(props.inspectionData)
    } else {
      resetForm()
    }
  }
})

// 关闭弹窗
const handleClose = () => {
  visible.value = false
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    const submitData = { ...formData }
    
    if (isEdit.value) {
      await updateInspection(submitData)
      ElMessage.success('更新成功')
    } else {
      await saveInspection(submitData)
      ElMessage.success('保存成功')
    }
    
    emit('success')
    handleClose()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>